import os
import yaml
import pandas as pd
from pymongo import MongoClient
from WindPy import w


def load_config():
    try:
        with open("config.yaml", 'r', encoding='utf-8') as f:
            data = yaml.load(f.read(), yaml.FullLoader)
        print("loading_config ... >>> 读取本地配置")
    except:
        conn = MongoClient("mongodb://hf_user:290202@192.168.3.179:27017/?authSource=admin")
        coll = conn['project_config']['commodity']
        data = list(coll.find())[-1]
        print("loading_config ... >>> 读取服务器配置")
    return data


def load_config_():
    with open("config.yaml", 'r', encoding='utf-8') as f:
        data = yaml.load(f.read(), yaml.FullLoader)
    print("读取本地配置")
    return data


def get_tushare_code_to_exchange(cfg: dict):
    exchange_dic = cfg['exchange']
    new_dic = {}
    for exchange, name_dic in exchange_dic.items():
        for chinese_name, v_li in name_dic.items():
            new_dic[v_li[1]] = exchange
    return new_dic


def get_chinese_name_to_ts_code(cfg: dict):
    exchange_dic = cfg['exchange']
    new_dic = {}
    for exchange, name_dic in exchange_dic.items():
        for chinese_name, v_li in name_dic.items():
            new_dic[chinese_name] = v_li[1]
    return new_dic


def get_ts_code_to_chinese_name(cfg: dict):
    exchange_dic = cfg['exchange']
    new_dic = {}
    for exchange, name_dic in exchange_dic.items():
        for chinese_name, v_li in name_dic.items():
            new_dic[v_li[1]] = chinese_name
    return new_dic


def get_chinese_name_to_wind_code(cfg: dict):
    exchange_dic = cfg['exchange']
    new_dic = {}
    for exchange, name_dic in exchange_dic.items():
        for chinese_name, v_li in name_dic.items():
            new_dic[chinese_name] = v_li[0]
    return new_dic


def get_ts_code_to_pred_code_map(cfg:dict):
    exchange_dic = cfg['exchange']
    new_dic = {}
    for exchange, name_dic in exchange_dic.items():
        for chinese_name, v_li in name_dic.items():
            new_dic[v_li[1]] = v_li[2]
    return new_dic


def loc_collection(db_name, collection_name, cfg={}):
    if len(cfg) == 0:
        cfg = load_config()
    conn = MongoClient(cfg['mongodb'])
    coll_ = conn[db_name][collection_name]
    return coll_


def loc_db(db_name, cfg={}):
    if len(cfg) == 0:
        cfg = load_config()
    return MongoClient(cfg['mongodb'])[db_name]


def loc_zq_collection(db_name, collection_name):
    conn = MongoClient("mongodb://192.168.1.9:27017")
    coll_ = conn[db_name][collection_name]
    return coll_


def download_wind_edb(dic: dict):
    if not w.isconnected():
        w.start()
    wind_id = dic['指标ID']
    c_nn = dic['指标名称']
    update_date = dic['update_date']
    resp = w.edb(wind_id, "2012-01-01", update_date)
    if int(resp.ErrorCode) == 0:
        dic['t'] = [str(s)[:10] for s in resp.Times]
        v_li = resp.Data[0]
        dic['v'] = v_li
        print(f"抓取名称:{c_nn}成功，{len(v_li)}个,")
    else:
        print(f"想要抓取wind_id:>{wind_id}:名称:{c_nn}失败，错误码{resp.ErrorCode}")
    # print('errorcode', resp.ErrorCode)
    return dic


def find_spot_or_stock_by_ts_code(cfg: dict, ts_code_lower: str, mode: str):
    print("loading_config", len(cfg))
    collctiion_map = {'库存': 'future_stock_data', '现货': 'future_spot_price'}
    collection_ = loc_collection('project_config', collctiion_map[mode])
    spot_li = list(collection_.find({'ts_code': ts_code_lower}))
    spot_data = {}
    for va in spot_li:
        spot_data[va['指标名称']] = pd.DataFrame(data=va['v'], index=va['t'], columns=[va['指标名称']])
    return spot_data, {}


def first_second_dir_exists(name):
    path1 = "../it_data"
    if not os.path.exists(path1):
        os.makedirs(path1)
    path2 = f"{path1}/{name}"
    if not os.path.exists(path2):
        os.makedirs(path2)
    return path2


def first_dir_exists():
    path1 = "../it_data"
    if not os.path.exists(path1):
        os.makedirs(path1)
    return path1


def concat_and_build_dir(dir1, name):
    ot_path = f"{dir1}/{name}"
    if not os.path.exists(ot_path):
        os.makedirs(ot_path)
    return ot_path


def check_str(pth: str):
    """
    保证保存的字符串路径符合windows文件要求
    :param pth:
    :return:
    """
    li = [':', '*', '?', '"', '<', '>', '|']
    for s in li:
        pth = pth.replace(s, '_')
    return pth


if __name__ == "__main__":
    conf = load_config()
    # d = get_tushare_code_to_exchange(conf)
    dic_ = {'指标ID': 'S5023663', '指标名称': 'tong', 'update_date': '2021-12-24'}
    dic_d = download_wind_edb(dic_)
